<template>
  <div class="box">
    <h1>To-Do List</h1>
    <h3>{{ time }}</h3>
    <div class="todo">
      <input
        type="text"
        v-model="newItem"
        placeholder="Add new item"
        @keydown="handleKeyDown"
      />
      <el-button type="primary" @click="addItem" plain>添加待办</el-button>
    </div>
  </div>
  <ToDolistBody :todos="todos"></ToDolistBody>
  <div class="footer" v-if="isShow">
    <ToDolistFooter :todos="todos"></ToDolistFooter>
  </div>
  <div class="no-todo" v-else>
    <p>暂无待办事项</p>
  </div>
  <Reward v-if="!isShow"/>
</template>

<script setup>
import ToDolistBody from './ToDolistBody.vue'
import ToDolistFooter from './ToDolistFooter.vue'
import Reward from './Reward.vue'
import { ref, computed, onMounted, watch } from 'vue'
let item = ref({})
const newItem = ref('')
let todos = ref([
  { id: 1, text: '吃饭', done: true, isShow: true },
  { id: 2, text: '睡觉', done: false, isShow: true },
  { id: 3, text: '打豆豆', done: false, isShow: true },
])
const addItem = () => {
  if (newItem.value) {
    item.value = {
      id: todos.value.length + 1,
      text: newItem.value,
      done: false,
      isShow: true,
    }
    todos.value.push(item.value)
    newItem.value = ''
  }
}
const handleKeyDown = (e) => {
  if (e.key === 'Enter') {
    addItem()
  }
}
const isShow = computed(() => {
  return todos.value.length > 0
})
const time = ref('')
setInterval(() => {
  return (time.value = new Date().toLocaleString())
})

watch(
  () => todos.value,
  () => {
    localStorage.setItem('todos', JSON.stringify(todos.value))
  },
  { deep: true }
)

onMounted(() => {
  if (localStorage.getItem('todos')) {
    const arr = ref(JSON.parse(localStorage.getItem('todos')))
    console.log(arr.value)
    todos.value = arr.value
  }
})

// localStorage.clear()
</script>

<style scoped>
.box {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid black;
  padding: 0 0 10px 0;
}
.todo {
  display: flex;
}
h1 {
  color: aliceblue;
  margin: 20px 0 5px;
}
h3 {
  color: #333;
  margin: 0;
  font-size: 20px;
}

input {
  width: 300px;
  margin-right: 10px;
}
.footer {
  width: 100%;
}
.no-todo {
  text-align: center;
  width: 100%;
  border-bottom: 1px solid black;
}
</style>
